package crudfx.util;
import javax.swing.*;
import java.io.*;
/**
 * @profile desktop
 * @author Sergey Surikov
 */
public class FileDialog {
  public var folder:String;
  public var extensions:String[];
  public var file:String;
  public var description:String;
  public var directory:Boolean=false;
  var chooser:JFileChooser=new JFileChooser();
  var filter:javax.swing.filechooser.FileFilter;
  public function open(action:function():Void):Void{
      setFolder();
      var r:Integer=chooser.showOpenDialog(null);
      if(r==chooser.APPROVE_OPTION){
          readFolder();
          //file=chooser.getSelectedFile().getAbsolutePath();
          readFile();
          action();
          }
      }
  public function save(action:function():Void):Void{
      setFolder();
      var r:Integer=chooser.showSaveDialog(null);
      if(r==chooser.APPROVE_OPTION){
          readFolder();
          //file=chooser.getSelectedFile().getAbsolutePath();
          readFile();
          action();
          }
      }
  function setFolder():Void{
      try {
          if(directory) chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY)
            else chooser.setFileSelectionMode(JFileChooser.FILES_ONLY );

          chooser.setCurrentDirectory(new File(folder));
          } 
      catch(e){
          ConsoleIO.error(this,e);
          }
      }
  function readFolder():Void{
      try {
          folder=chooser.getCurrentDirectory().getAbsolutePath();
          } 
      catch(e){
          ConsoleIO.error(this,e);
          }
      }
  function readFile():Void{
      file=chooser.getSelectedFile().getAbsolutePath();
      if((sizeof extensions)>0){
          for(s:String in extensions){
                //println(s);
                if(file.toUpperCase().endsWith(s.toUpperCase())){
                  return;
                  }
                }
          file="{file}{extensions[0]}";
          }
      }
  init{
      chooser.setFileHidingEnabled(false);
      chooser.setMultiSelectionEnabled(false);
      filter=javax.swing.filechooser.FileFilter{
          override public function accept(file: File):Boolean{
              //println(file);
              if(file.isDirectory()){
                  return true;
                  }
              for(s:String in extensions){
                //println(s);
                if(file.getAbsolutePath().toUpperCase().endsWith(s.toUpperCase())){
                  return true;
                  }
                }
              return false;
              }
          override public function getDescription() :String{
              return description;
              };
          };
      chooser.setFileFilter(filter);
      }
  }
